package com.appspot.redalert;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
import android.content.Context;

import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;



class DataSource  {
	private static final String DATABASE_NAME = "com.appspot.redalert";
	private static final int DATABASE_VERSION = 1;
	private Log mLog;
	private SQLiteDatabase mDb;

	private static final String DATABASE_CREATE =
		"CREATE TABLE persons (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
		+ "contact_id integer not null);";
	private static final String DATABASE_DROP =
		"DROP TABLE IF EXISTS persons;";

	/**
	 * This class helps open, create, and upgrade the database file.
	 */
	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, 
				int newVersion) {
			Log.getInstance().w("Upgrading database from version " + oldVersion 
					+ " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL(DATABASE_DROP);
			onCreate(db);
		}
	}
	private DatabaseHelper mOpenHelper;

	DataSource(Context context) {
		//super(context, DATABASE_NAME, null, DATABASE_VERSION);
		mDb = context.openOrCreateDatabase(DATABASE_NAME, 0,null);

		mLog = Log.getInstance();
	}

	void create() {
		try {
			mDb.execSQL(DATABASE_CREATE);
		} catch(SQLiteException sqle) {
			mLog.w("Ignoring " + sqle);
		}
	}
	
	void drop() {
		try {
			mDb.execSQL(DATABASE_DROP);
		} catch(SQLiteException sqle) {
			mLog.w("Ignoring " + sqle);
		}
	}
	
	boolean check() {
		Set<String> table_set = new HashSet<String>(10);
		Cursor c;
		try {
			c = mDb.rawQuery(
					"SELECT name FROM sqlite_master WHERE type = \"table\"", null);
			if(c != null) {
				if (c.moveToFirst()) {
					do {
						table_set.add(c.getString(0));
					} while(c.moveToNext());
				}
				c.close();
			}
		} catch(SQLiteException sqle) {
			mLog.e("Error " + sqle);
			return false;
		}
		return table_set.containsAll(Arrays.asList(new String[]{"persons"}));
	}

}
